<template>
    <el-card>
        <div class="box">
            <div class="short"></div>
            <div>医生管理</div>
        </div>
        <div class="select-container">
            <div class="select-box">
                <span class="span">所属机构</span>
                <el-select size="large" style="width: 200px;" placeholder="请选择" v-model="searchData.organizationId"
                    clearable>
                    <el-option v-for="item in AgencyData.rows" :key="item._id" :label="item.name" :value="item._id" />
                </el-select>
            </div>
            <div class="select-box">
                <span class="span">所属团队</span>
                <el-select size="large" style="width: 200px;" placeholder="请选择" v-model="searchData.teamId" clearable>
                    <el-option v-for="item in TeamData.rows" :key="item._id" :label="item.name" :value="item._id" />
                </el-select>
            </div>
            <div class="select-box">
                <span class="span">医生标签</span>
                <el-select size="large" style="width: 200px;" placeholder="请选择" v-model="searchData.tag" clearable>
                    <el-option v-for="item in TagsData.rows" :key="item._id" :label="item.name" :value="item._id" />
                </el-select>
            </div>
            <div class="btn-box">
                <el-button size="large" v-permission="'新增医生'"
                    @click="$router.push('/data/doctor/add')">新增医生信息</el-button>
                <el-button size="large">导出</el-button>
            </div>
        </div>
        <div class="select">
            <div class="input-box">
                <el-input type="text" placeholder="请输入关键字" v-model="searchData.name" clearable />
                <img src="../../../assets/teamManage/u1347.png">
            </div>
            <div class="select-role">
                <span class="span">医生角色</span>
                <el-select size="large" style="width: 200px;" placeholder="请选择" v-model="searchData.roleId" clearable>
                    <el-option v-for="item in roleData.rows" :key="item._id" :label="item.name" :value="item._id" />
                </el-select>
            </div>
        </div>
        <el-table :data="doctorsData.rows" :header-cell-style="{ textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }" style="margin-top: 30px;">
            <el-table-column type="selection" width="55" />
            <el-table-column label="编号" prop="_id" show-overflow-tooltip />
            <el-table-column label="头像">
                <template #default="{ row }">
                    <el-image v-if="row.avatar" :src="row.avatar" style="width: 50px; height: 50px;"></el-image>
                    <el-tag v-else round>未上传</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="姓名" prop="name" />
            <el-table-column label="联系电话" prop="phone" />
            <el-table-column label="角色" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.roleId.name }}
                </template>
            </el-table-column>
            <el-table-column label="所属团队">
                <template #default="{ row }">
                    {{row.teamIds.map(item => item.name).join('')}}
                </template>
            </el-table-column>
            <el-table-column label="所属机构" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.organizationId?.name }}
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template #default="{ row }">
                    <el-switch v-model="row.state" active-text="启用" inactive-text="禁用" :active-value="1"
                        :inactive-value="0" inline-prompt
                        style="--el-switch-on-color:#13ec66; --el-switch-off-color: #ccc"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
                <template #default="{ row }">
                    <div class="action-buttons">
                        <el-button type="primary" v-permission="'医生详情'" link @click="$router.push({
                            path: '/data/doctor/detail/:_id',
                            query: { _id: row._id }
                        })">查看详情</el-button>
                        <el-button type="primary" link>发消息</el-button>
                        <el-button type="primary" v-permission="'编辑医生'" link @click="$router.push({
                            path: '/data/doctor/add',
                            query: { _id: row._id }
                        })">编辑</el-button>
                        <!-- {{ row._id }} -->
                        <el-button type="danger" link @click="deleteDoctor(row._id)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="flex-end" v-model:current-page="pageData.currentPage"
            v-model:page-size="pageData.pageSize" :page-sizes="[10, 20, 50, 100]" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="doctorsData.total" />
    </el-card>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { deleteDoctorApi, getDoctorsApi } from '../../../api/doctorManage';
import { useFindData } from '../../../composables/findData';
import { findRoleApi } from '../../../api/role';


onMounted(() => {
    getDoctors();
    findAgencyAsync();
    findTeamAsync();
    findTagsAsync();
    findRole()
})

const { AgencyData, findAgencyAsync, TeamData, findTeamAsync, TagsData, findTagsAsync } = useFindData()

const roleData = ref({
    rows: [],
    total: 0
})
//获取所有角色
function findRole() {
    findRoleApi()
        .then(res => {
            if (res.code == 200) {
                roleData.value.rows = res.data.rows,
                    roleData.value.total = res.data.total
            }
        })
}

//搜索条件
const searchData = ref({
    organizationId: '',
    teamId: '',
    name: '',
    tag: ''
})
// const selectedAgency = ref('');//选中机构
// const selectTeam = ref('')//选中团队
// const keyword = ref('');//关键字


//分页数据
const pageData = ref({
    currentPage: 1,
    pageSize: 5
})
//医生数据
const doctorsData = reactive({
    rows: [],
    total: 0
})

//查询医生方法
const getDoctors = async () => {
    const res = await getDoctorsApi({
        ...pageData.value,
        ...searchData.value,
    })
    if (res.code == 200) {
        console.log(res.data);

        doctorsData.rows = res.data.rows
        doctorsData.total = res.data.total
    }
}

//侦听分页数据
watch([pageData, searchData], () => {
    getDoctors();
}, { deep: true });

// 删除医生方法
function deleteDoctor(id) {
    ElMessageBox.confirm(
        '该操作不可撤销，确认删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 调用删除API并传递医生ID
            return deleteDoctorApi({ _id: id })
        })
        .then(res => {
            if (res.code === 200) {
                ElMessage.success('删除成功！')
                // 重新加载数据
                getDoctors()
            } else {
                throw new Error('删除失败')
            }
        })
        .catch(err => {
            if (err.name !== 'Cancel') { // 排除用户取消的情况
                console.error('删除失败：', err)
                ElMessage.error('删除失败，请重试')
            }
        })
}

</script>

<style scoped lang="scss">
.box {
    display: flex;
    align-items: center;

    div {
        font-size: 18px;
    }
}

.short {
    width: 6px;
    height: 20px;
    background-color: var(--el-color-primary);
    border-radius: 8px;
    margin-right: 10px;
}

.select-container {
    display: flex;
    position: relative;
    margin-top: 20px;

    span {
        margin: 0 15px;
        font-size: 13px;
        color: #999999;
    }

    .select-box {
        display: flex;
        align-items: center;
    }

    .btn-box {
        position: absolute;
        top: 0;
        right: 0;


        .el-button {
            background-color: var(--el-color-primary);
            color: #fff;
        }
    }

}

.select {
    display: flex;
    align-items: center;
    margin-top: 25px;
    margin-left: 15px;

    .input-box {
        width: 350px;
        height: 38px;
        border: 1px #ddd solid;
        border-radius: 4px;
        // margin-left: 15px;
        // margin-top: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        input {
            border: none;
            margin-left: 20px;

            &::-webkit-input-placeholder {
                /* Chrome/Safari */
                color: #999999;
                font-size: 14px;
            }
        }

        img {
            margin-right: 10px;
        }
    }

    .select-role {
        display: flex;
        align-items: center;
        height: 40px;

        span {
            margin: 0 15px;
            font-size: 13px;
            color: #999999;
        }
    }
}

.action-buttons {
    display: flex;
    justify-content: center;

    el-button el-button--primary is-link {
        padding: 0 4px; // 减少按钮内边距
        margin: 0 2px; // 减少按钮间距
    }
}

.el-input {
    --el-input-border-color: #ffffff;
    --el-input-hover-border-color: #ffffff;
    --el-input-focus-border-color: #ffffff
}
</style>